package com.example.concurrency.exercise;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedLongSynchronizer;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 * @author: dangwen
 * @createDate: 2021/2/19
 * 独占锁
 */
public class MyLockDemo1 implements Lock {

//    private Sync sync = new Sync();
    private Sync sync;

    public MyLockDemo1(){
        sync = new Sync();
    }

    private static class Sync extends AbstractQueuedLongSynchronizer{

        @Override
        protected boolean isHeldExclusively() {
            // 判断占有锁的线程是否是当前线程
            return getExclusiveOwnerThread() == Thread.currentThread();
        }

        @Override
        protected boolean tryAcquire(long arg) {
            // 如果获取锁成功，则将state改为1
            if(compareAndSetState(0,1)){
                setExclusiveOwnerThread(Thread.currentThread());
                return true;
            }
            return false;
        }

        @Override
        protected boolean tryRelease(long arg) {
            // 释放锁，重新将state置为0
            if(getState() == 0){
                throw new IllegalMonitorStateException();
            }
            setExclusiveOwnerThread(null);
            setState(0);
            return true;
        }

        Condition newCondition(){
            return new ConditionObject();
        }

    }
    @Override
    public void lock() {
        sync.acquire(1);
    }

    @Override
    public void unlock() {
        sync.release(1);
    }

    @Override
    public void lockInterruptibly() throws InterruptedException {

    }

    @Override
    public boolean tryLock() {
        return sync.tryAcquire(1);
    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return false;
    }

    @Override
    public Condition newCondition() {
        return sync.newCondition();
    }


    public static void main(String[] args) {
        MyLockDemo1 myLockDemo1 = new MyLockDemo1();

        // 每次只有一个线程能抢到锁，必须释放后，其他的线程才能获得锁
        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                myLockDemo1.lock();
                System.out.println(Thread.currentThread().getName()+"获得了锁");
                myLockDemo1.unlock();
                System.out.println(Thread.currentThread().getName()+"释放了锁");
            }).start();
        }

    }
}
